using net_work.Data.DTO.Appr;
using net_work.Data.Enum.Appr;
using NRules.Fluent.Dsl;

namespace net_work.Rules.Appr;

public class ApprovalRuleOnlyOne : Rule
{
    public override void Define()
    {
        Name("审批规则：OnlyOne");

        ApprovalSubmitInfo? submitInfo = null;

        When()
            .Match(() => submitInfo,
                s => s != null && s.SuccessType == NodeSuccessType.OnlyOne && s.HasHandled == false);

        Then().Do(context => UpdateApprovalSubmitInfo(submitInfo))
            .Do(context => context.Update(submitInfo));
    }

    private static void UpdateApprovalSubmitInfo(ApprovalSubmitInfo? submitInfo)
    {
        if (submitInfo == null)
        {
            return;
        }

        if (submitInfo.ProcessingType == NodeProcessingType.Teacher)
        {
            submitInfo.IsSkip = true;

            if (submitInfo.ApprovedCount >= 1)
            {
                submitInfo.SkipResult = true;
                submitInfo.HasHandled = true;
                return;
            }

            submitInfo.SkipResult = false;
            submitInfo.HasHandled = true;
            return;
        }

        if (submitInfo.ApprovedCount >= 1)
        {
            submitInfo.IsSkip = true;
            submitInfo.SkipResult = true;
            submitInfo.HasHandled = true;
            return;
        }

        if (submitInfo.UnApprovedCount < submitInfo.TaskTotalCount - 1)
        {
            submitInfo.HasHandled = true;
            return;
        }

        submitInfo.IsSkip = true;
        submitInfo.SkipResult = false;
        submitInfo.HasHandled = true;
    }
}